﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessLogic;

public static class MyCache
{
    public static T CheckCache<T>(string cacheKeyName)
    {
        T t = default(T);

        if (null != HttpRuntime.Cache[cacheKeyName])
        {
            t = (T)HttpRuntime.Cache[cacheKeyName];
        }

        return t;
    }

    public static void AddToCodeTableCache<T>(object cacheValue) where T : CodeTable<T>, new()
    {
        AddToCache(new T().CacheKeyName, cacheValue);
    }

    public static List<T> GetCodeTableCache<T>() where T : CodeTable<T>, new()
    {
        T t = new T();
        List<T> ts = null;

        if (!string.IsNullOrWhiteSpace(t.CacheKeyName))
        {
            ts = CheckCache<List<T>>(t.CacheKeyName);

            if (null == ts)
            {
                ts = t.GetAll();
                AddToCache(t.CacheKeyName, ts);
            }
        }

        return ts;
    }

    public static void RefreshCodeTableCache<T>(object cacheValue) where T: CodeTable<T>, new()
    {
        AddToCache(new T().CacheKeyName, cacheValue);
    }

    public static void RefreshCache(string cacheKeyName, object cacheValue)
    {
        //HttpRuntime.Cache.Insert overwrites 
        //what is currently stored in the cache
        //perfect for our "refresh"
        AddToCache(cacheKeyName, cacheValue);
    }

    public static void AddToCache(string cacheKeyName, object cacheValue)
    {
        HttpRuntime.Cache.Insert(cacheKeyName, cacheValue);        
    }
}